<template>
    <div ref="chartRef" class="chart-container" :style="{
        width: responsive ? '100%' : '100%',
        height: responsive ? '100%' : '400px',
    }"></div>
</template>

<script setup>
import * as echarts from "echarts/core";
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DataZoomComponent,
    ToolboxComponent
} from "echarts/components";
import { BarChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import { onMounted, nextTick, onUnmounted, ref, watch, onActivated } from "vue";
import { debounce } from "@/utils/DebounceAndThrottle";

echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DataZoomComponent,
    ToolboxComponent,
    BarChart,
    CanvasRenderer,
]);

const props = defineProps({
    data: {
        type: Array,
        default: () => [
            { name: "项目A", value: 340 },
            { name: "项目B", value: 280 },
            { name: "项目C", value: 220 },
            { name: "项目D", value: 180 },
            { name: "项目E", value: 150 }
        ]
    },
    title: {
        type: String,
        default: "排行榜"
    },
    responsive: {
        type: Boolean,
        default: true
    },
    horizontal: {
        type: Boolean,
        default: true // true为水平排列（当前样式），false为垂直排列
    }
});

const chartRef = ref(null);
let chartInstance = null;
let resizeObserver = null;

// 使用防抖来处理resize
const debouncedResize = debounce(() => {
    if (chartInstance) {
        const currentAnimation = chartInstance.getOption().animation;
        chartInstance.setOption({
            animation: false
        });
        chartInstance.resize();
        chartInstance.setOption({
            animation: currentAnimation
        });
    }
}, 1000);

const handleResize = () => {
    debouncedResize();
};

const updateChart = () => {
    if (!chartInstance || !props.data) return;

    // 对数据进行排序
    const sortedData = [...props.data].sort((a, b) => b.value - a.value).map(item => ({
        name: item.name,
        value: +item.value.toFixed(2)
    }));

    // 根据horizontal属性配置不同的轴
    const axisConfig = props.horizontal ? {
        // 水平排列：y轴为类别轴，x轴为数值轴
        xAxis: {
            type: 'value',
            axisTick: { show: false },
            axisLine: {
                show: false,
                lineStyle: { color: "#aaa", width: 1 }
            },
            splitLine: {
                show: true,
                lineStyle: { color: "#f0f0f0", type: "dashed" }
            },
            axisLabel: { show: false }
        },
        yAxis: {
            type: 'category',
            data: sortedData.map(item => item.name),
            axisTick: { show: false },
            axisLine: {
                show: false,
                lineStyle: { color: "#aaa", width: 1 }
            },
            inverse: true
        },
        dataZoom: [
            {
                type: 'slider',
                yAxisIndex: 0,
                right: '2%',
                width: 18,
                start: 0,
                end: sortedData.length <= 10 ? 100 : (10 / sortedData.length) * 100,
                zoomLock: false,
                moveOnMouseWheel: false,
                zoomOnMouseWheel: false,
                moveOnMouseMove: true,
                show: sortedData.length > 10
            },
            {
                type: 'inside',
                yAxisIndex: 0,
                zoomOnMouseWheel: false,
                moveOnMouseWheel: true,
                preventDefaultMouseMove: false,
                throttle: 50
            }
        ],
        itemStyle: {
            color: colorPalette[0],
            borderRadius: [0, 4, 4, 0]
        },
        barMaxWidth: 30  // 修改：横向模式下最大宽度限制为30
    } : {
        // 垂直排列：x轴为类别轴，y轴为数值轴
        xAxis: {
            type: 'category',
            data: sortedData.map(item => item.name),
            axisTick: { show: false },
            axisLine: {
                show: false,
                lineStyle: { color: "#aaa", width: 1 }
            },
            axisLabel: {
                rotate: 0,
                interval: 0
            }
        },
        yAxis: {
            type: 'value',
            axisTick: { show: false },
            axisLine: {
                show: false,
                lineStyle: { color: "#aaa", width: 1 }
            },
            splitLine: {
                show: true,
                lineStyle: { color: "#f0f0f0", type: "dashed" }
            },
            axisLabel: { show: false }
        },
        dataZoom: [
            {
                type: 'slider',
                xAxisIndex: 0,
                bottom: 0,
                start: 0,
                end: sortedData.length <= 10 ? 100 : (10 / sortedData.length) * 100,
                zoomLock: false,
                moveOnMouseWheel: false,
                zoomOnMouseWheel: false,
                moveOnMouseMove: true
            },
            {
                type: 'inside',
                xAxisIndex: 0,
                zoomOnMouseWheel: false,
                moveOnMouseWheel: true,
                preventDefaultMouseMove: false,
                throttle: 50
            }
        ],
        itemStyle: {
            color: colorPalette[0],
            borderRadius: [4, 4, 0, 0]
        },
        barMaxWidth: 60  // 垂直模式保持原来的60
    };

    const option = {
        backgroundColor: "#ffffff",
        title: {
            textStyle: {
                fontSize: 16,
                fontWeight: 500,
                color: "#333",
            },
            top: 10,
            left: "3%",
        },
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    type: 'png',
                    title: '保存为图片',
                    pixelRatio: 2,
                    backgroundColor: '#fff'
                }
            },
            right: '20px',
            top: '2px'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            top: '8%',
            right: props.horizontal ? (props.data.length <= 10 ? '5%' : '10%') : '5%',
            bottom: props.horizontal ? '0%' : (props.data.length <= 10 ? '5%' : '15%'),
            left: '5%',
            containLabel: true
        },
        xAxis: axisConfig.xAxis,
        yAxis: axisConfig.yAxis,
        dataZoom: axisConfig.dataZoom,
        series: [
            {
                type: 'bar',
                data: sortedData.map(item => item.value),
                itemStyle: axisConfig.itemStyle,
                barMaxWidth: props.horizontal ? 30 : 60,  // 修改：根据horizontal属性动态设置最大宽度
                barWidth: props.horizontal ? 30 : 60,     // 修改：根据horizontal属性动态设置宽度
                emphasis: {
                    itemStyle: {
                        color: colorPalette[1]
                    }
                },
                animation: true,
                animationDuration: 500,
                animationEasing: "cubicInOut"
            }
        ]
    };

    chartInstance.setOption(option);
};

const initChart = () => {
    if (!chartRef.value) return;

    // 如果已经存在实例，先销毁
    if (chartInstance) {
        chartInstance.dispose();
    }

    // 初始化图表
    chartInstance = echarts.init(chartRef.value);
    updateChart();

    // 设置resize观察器
    if (resizeObserver) {
        resizeObserver.disconnect();
    }
    resizeObserver = new ResizeObserver(handleResize);
    resizeObserver.observe(chartRef.value);

    // 添加window resize监听
    window.addEventListener("resize", handleResize);
};

// 监听数据变化
watch(() => props.data, () => {
    nextTick(() => {
        updateChart();
    });
}, { deep: true });

// 监听horizontal属性变化
watch(() => props.horizontal, () => {
    nextTick(() => {
        updateChart();
    });
});

// 组件激活时重新初始化图表
onActivated(() => {
    nextTick(() => {
        initChart();
    });
});

onMounted(() => {
    nextTick(() => {
        initChart();
    });
});

onUnmounted(() => {
    if (resizeObserver) {
        resizeObserver.disconnect();
        resizeObserver = null;
    }
    if (chartInstance) {
        window.removeEventListener('resize', handleResize);
        chartInstance.dispose();
        chartInstance = null;
    }
});

const colorPalette = [
    "#409EFF",
    "#7dafff",
    "#ee7a18",
    "#67C23A",
    "#E6A23C",
    "#F56C6C",
    "#909399",
];
</script>

<style scoped>
.chart-container {
    position: relative;
    min-height: 200px;
    width: 100%;
}
</style>